<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>用户管理</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: '微软雅黑';
            background: rgb(255, 255, 255);

        }

        .main-content {
            width: 100%;
            padding: 24px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .action-bar {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
        }

        input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 160px;
            font-size: 13px;
        }

        button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
        }

        .btn-search {
            background: #1890ff;
            color: white;
        }

        .btn-new {
            background: #52c41a;
            color: white;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border: 1px solid #e8e8e8;
            margin-top: 12px;
        }

        th, td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid #e8e8e8;
            font-size: 13px;
        }

        th {
            background: #fafafa;
            color: rgba(0, 0, 0, 0.85);
        }

        .action-btns button {
            padding: 4px 8px;
            margin-right: 8px;
        }

        .btn-edit {
            background: #faad14;
            color: #fff;
        }

        .btn-del {
            background: #ff4d4f;
            color: #fff;
        }

        .pagination {
            margin-top: 16px;
            color: #999;
            font-size: 13px;
        }
    </style>
</head>
<body>
<div class="main-content">
    <h3 style="margin-bottom:16px;color:rgba(0,0,0,0.85)">用户管理</h3>
    <div class="action-bar">
        <input placeholder="用户名" name="username" id="username">

        <button id="searchBtn" class="btn-search">查询</button>
        


        <button type="button" class="btn-new" onclick="openAddModal()">新增</button>
    </div>
    <!-- 修改表格结构 -->
    <table id="userTable">
        <thead>
        <tr>
            <th>用户名</th>
            <th>电话</th>
            <th>角色</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <!-- 修改表单结构 -->
    <%--    <form id="searchForm" onsubmit="return false;">--%>
    <%--        <div class="action-bar">--%>
    <%--            <input placeholder="用户名" name="username">--%>
    <%--            <button type="button" class="btn-search" onclick="searchUsers()">查询</button>--%>
    <%--            <button type="button" class="btn-new" onclick="openAddModal()">新增</button>--%>
    <%--        </div>--%>
    <%--    </form>--%>

    <!-- 修改分页控件 -->
    <div class="pagination">
        <button id="prevPage" class="btn-prev" onclick="prevPage()">上一页</button>
        <span id="pageInfo">第1页/共1页</span><span style="margin-left: 10px;"></span>
        <button id="nextPage" class="btn-next" onclick="nextPage()">下一页</button>
    </div>
</div>
<!-- 添加新增用户的模态框 -->
<div id="addModal"
     style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 999;">
    c
    <div style="position: relative; background: white; width: 400px; margin: 100px auto; padding: 20px; border-radius: 8px;">
        <h3 style="margin-bottom: 20px;">新增用户</h3>
        <div style="margin-bottom: 16px;">
            <label>用户名：</label>
            <input type="text" name="username1" required style="width: 100%; padding: 8px;">
        </div>
        <div style="margin-bottom: 16px;">
            <label>密码：</label>
            <input type="password" name="password" required style="width: 100%; padding: 8px;">
        </div>
        <div style="margin-bottom: 16px;">
            <label>电话：</label>
            <input type="tel" name="phone" style="width: 100%; padding: 8px;">
        </div>
        <div style="margin-bottom: 20px;">
            <label>角色：</label>
            <select name="role" style="width: 100%; padding: 8px;">
                <option value="student">学生</option>
                <option value="dormitory">宿管</option>
            </select>
        </div>
        <!-- 在新增模态框中 -->
        <div style="margin-bottom:15px;">
            <label>性别：</label>
            <select name="sex" style="width:100%;padding:8px;">
                <option value="男">男</option>
                <option value="女">女</option>
            </select>
        </div>
        <div style="text-align: right;">
            <button type="button" onclick="closeAddModal()" style="margin-right: 10px;">取消</button>
            <button type="button" onclick="submitAddForm()" style="background: #1890ff; color: white;">提交</button>
        </div>
    </div>
</div>
<!-- 在新增模态框后面添加编辑模态框 -->
<div id="editModal"
     style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:1000;">
    <div style="position:relative;width:400px;margin:100px auto;padding:20px;background:#fff;border-radius:8px;">
        <h3 style="margin-bottom:20px;">编辑用户</h3>
        <form id="editForm">
            <input type="hidden" id="editUserId" name="user_id">
            <div style="margin-bottom:15px;">
                <label>用户名：</label>
                <input type="text" id="editUsername" name="username" required style="width:100%;padding:8px;">
            </div>
            <div style="margin-bottom:15px;">
                <label>电话：</label>
                <input type="tel" id="editPhone" name="phone" style="width:100%;padding:8px;">
            </div>
            <div style="margin-bottom:15px;">
                <label>性别：</label>
                <select id="editSex" name="sex" style="width:100%;padding:8px;">
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>
            <div style="margin-bottom:15px;">
                <label>角色：</label>
                <select id="editRole" name="role" style="width:100%;padding:8px;">
                    <option value="student">学生</option>
                    <option value="dormitory">宿管</option>
                </select>
            </div>
            <div style="text-align:right;">
                <button type="button" onclick="closeEditModal()" style="margin-right:10px;">取消</button>
                <button type="button" onclick="submitEditForm()" style="background:#1890ff;color:white;">提交</button>
            </div>
        </form>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script>
    $(document).ready(function() {
        $('#searchBtn').click(getcx);
    });
    // 打开新增模态框
    function openAddModal() {
        document.getElementById("addModal").style.display = "block";
    }

    // 关闭新增模态框
    function closeAddModal() {
        document.getElementById("addModal").style.display = "none";
    }

    // 提交新增表单
    function submitAddForm() {
        const formData = {
            username: $('[name="username1"]').val(),
            password: $('[name="password"]').val(),
            confirmPwd: $('[name="confirmPwd"]').val(),
            phone: $('[name="phone"]').val(),
            role: $('[name="role"]').val(),
            sex: $('[name="sex"]').val()  // 修正这里，原代码是$('[sex="sex"]').val()
        };

        $.ajax({
            url:'<%=request.getContextPath()%>/User_MangementController',
            type:'POST',
            data:{
                op:"insert",
                username: formData.username,
                password: formData.password,
                phone: formData.phone,
                role: formData.role,
                sex: formData.sex
                        },
                    dataType:'json',
            success:function (response) {
                if (response && response.success) {
                    alert(response.message || '新增成功');
                    closeAddModal();
                    // 刷新用户列表（这里需要根据你的实际接口实现）
                    loadViolations();
                } else {
                    alert(response.message || '新增失败')




                }
            }
        })
    }

    //页面加载时获取用户数据
    $(document).ready(function () {
        getcx();
    });


    // 在script标签顶部添加分页变量
    let currentPage = 1;
    let totalPages = 1;
    const pageSize = 5; // 修改为每页5条数据

    // 修改getcx函数支持分页
    // 确保getcx函数定义在全局作用域
    window.getcx = function() {
        let username = $("#username").val();
        
        $.post('<%=request.getContextPath()%>/User_MangementController', {
            op: "search",
            username: username,
            page: currentPage,
            pageSize: pageSize
        }, function(response) {
            if (typeof response === 'string') {
                try {
                    response = JSON.parse(response);
                } catch (e) {
                    console.error('JSON解析错误:', e);
                    return;
                }
            }
    
            // 更新分页信息
            currentPage = response.currentPage || 1;
            totalPages = response.totalPages || 1;
            updatePaginationUI();
        
            // 渲染表格数据
            let html = "";
            if (response.data && response.data.length > 0) {
                $.each(response.data, function(index, emp) {
                    // 将角色转换为中文显示
                    const roleText = emp.role === 'dormitory' ? '宿管' : 
                               (emp.role === 'student' ? '学生' : emp.role);

                    html += '<tr>' +
                        '<td>' + emp.username + '</td>' +
                        '<td>' + emp.phone + '</td>' +
                        '<td>' + roleText + '</td>' +
                        '<td class="action-btns">' +
                        '<button class="btn-edit" onclick="openEditModal(\'' + emp.user_id + '\',\'' + emp.username + '\',\'' + emp.phone + '\',\'' + emp.role + '\',\'' + emp.sex + '\')">修改</button>' +
                        '<button class="btn-del" onclick="deleteUser(\'' + emp.user_id + '\')">删除</button>' +
                        '</td>' +
                        '</tr>';
                });
            } else {
                html = '<tr><td colspan="4" style="text-align:center;">暂无数据</td></tr>';
            }
            $("#userTable tbody").html(html);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            console.error("查询失败:", textStatus, errorThrown);
        });
    }
    function show(data) {
        let data1 = JSON.parse(data);
        let htmls = "";
        $.each(data1, function (index, emp) {
            htmls += '<div class="student-card" draggable="true">' +
                '<div class="status-led available"></div>' +
                emp.student_number + '-' + emp.name + '(' + emp.gender + ')' +
                '</div>';
        });
        $("#div2").html(htmls);
    }
    function deleteUser(userId) {
        if (!userId || isNaN(userId)) {
            alert('无效的用户ID');
            return;
        }
        
        // 获取当前按钮元素，用于显示加载状态
        const $deleteBtn = $(`button[onclick="deleteUser('${userId}')"]`);
        const originalText = $deleteBtn.text();
        $deleteBtn.text('删除中...').prop('disabled', true);
        
        if (!confirm('确定要删除这个用户吗？此操作不可撤销！')) {
            $deleteBtn.text(originalText).prop('disabled', false);
            return;
        }
    
        $.ajax({
            url: '<%=request.getContextPath()%>/User_MangementController',
            type: 'POST',
            data: {
                op: 'delete',
                user_id: userId
            },
            dataType: 'json',
            success: function(response) {
                if (response && response.success) {
                    alert(response.message || '用户删除成功');
                    getcx(); // 刷新列表
                } else {
                    alert(response ? response.message : '删除失败: ' + (response.error || '未知错误'));
                }
            }
        });
    }

    // 打开编辑模态框
    function openEditModal(userId, username, phone, role, sex) {
        $('#editUserId').val(userId);
        $('#editUsername').val(username);
        $('#editPhone').val(phone);
        $('#editRole').val(role);
        $('#editSex').val(sex);
        $('#editModal').show();
    }

    // 关闭编辑模态框
    function closeEditModal() {
        $('#editModal').hide();
    }

    // 提交编辑表单
    function submitEditForm() {
        const formData = {
            user_id: $('#editUserId').val(),
            username: $('#editUsername').val(),
            phone: $('#editPhone').val(),
            sex: $('#editSex').val(),
            role: $('#editRole').val()
        };

        $.ajax({
            url: '<%=request.getContextPath()%>/User_MangementController',
            type: 'POST',
            data: $.param({...formData, op: 'update'}),
            dataType: 'json',
            success: function (response) {
                if (response && response.success) {
                    alert('修改成功');
                    closeEditModal();
                    getcx(); // 刷新列表
                } else {
                    alert(response ? response.message : '无效的服务器响应');
                }
            },
            error: function (xhr, status, error) {
                try {
                    const errResponse = JSON.parse(xhr.responseText);
                    alert(errResponse.message || '请求失败');
                } catch (e) {
                    alert('请求失败: ' + error);
                }
            }
        });
    }

    // 添加分页相关函数
    function updatePaginationUI() {
        $("#pageInfo").text("第" + currentPage + "页/共" + totalPages + "页");
        $("#prevPage").prop("disabled", currentPage <= 1);
        $("#nextPage").prop("disabled", currentPage >= totalPages);
    }

    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            getcx();
        }
    }

    function nextPage() {
        if (currentPage < totalPages) {
            currentPage++;
            getcx();
        }
    }
</script>
</body>
</html>